import React, { Component, Fragment } from "react";
import { Table, Form, Modal, Button, message, Input, Popconfirm, Upload } from "antd";
import { adminToken } from "@/utils/variable";
import { PlusOutlined } from "@ant-design/icons";
import { getAllCat, addCat, deleteCat, updateCat } from "@/api/commodity";
const { Item: FormItem } = Form;
export class Category extends Component {
    constructor() {
        super();
        this.state = {
            columns: [
                {
                    title: "分类名",
                    dataIndex: "title",
                },
                {
                    title: "分类图片",
                    dataIndex: "cover",
                    render: text => <Fragment>{text ? <img width="50" src={`${process.env.REACT_APP_FILE}/${text}`} /> : ""}</Fragment>,
                },
                {
                    title: "排序号",
                    dataIndex: "orderIndex",
                },
                {
                    title: "操作",
                    width: 200,
                    dataIndex: "operation",
                    render: (text, { title, _id, cover, orderIndex }) => (
                        <div className="operation-wrap">
                            <Button
                                type="primary"
                                onClick={() => {
                                    this.setState(
                                        {
                                            FormModalVisible: true,
                                            editId: _id,
                                            isAdd: false,
                                            cover,
                                        },
                                        () => this.refs.categoryFormRef.setFieldsValue({ title, cover, orderIndex })
                                    );
                                }}
                            >
                                编辑
                            </Button>
                            <Popconfirm
                                title={`确定删除${title}吗？`}
                                okText="确定"
                                cancelText="取消"
                                onConfirm={() => {
                                    deleteCat({ _id }).then(res => {
                                        if (res.code === 200) {
                                            this.getAllCat_com();
                                            message.success("删除成功");
                                        } else {
                                            message.warn(res.message);
                                        }
                                    });
                                }}
                            >
                                <Button danger>删除</Button>
                            </Popconfirm>
                        </div>
                    ),
                },
            ],
            dataSource: [],
            FormModalVisible: false,
            isAdd: true,
            editId: null,
            cover: null,
            pagination: {
                current: 1,
                pageSize: 10,
                total: 0,
                onChange: (current, pageSize) => {
                    this.setState({ pagination: { ...this.state.pagination, current, pageSize } }, () => {
                        this.getAllCat_com();
                    });
                },
            },
        };
    }
    UNSAFE_componentWillMount() {
        this.getAllCat_com();
    }
    getAllCat_com = () => {
        const { current, pageSize } = this.state.pagination;
        getAllCat({ current, pageSize }).then(res => {
            if (res.code === 200) {
                this.setState({
                    dataSource: res.data.sort((a, b) => b - a).map(item => ({ ...item, key: item._id })),
                    pagination: { ...this.state.pagination, total: res.total },
                });
            }
        });
    };
    render() {
        const { columns, dataSource, FormModalVisible, isAdd, editId, cover, pagination } = this.state;
        return (
            <>
                <div className="mb-10">
                    <Button
                        type="primary"
                        onClick={() => {
                            this.setState({ FormModalVisible: true }, () => this.refs.categoryFormRef.resetFields());
                        }}
                    >
                        添加分类
                    </Button>
                </div>
                <Table columns={columns} dataSource={dataSource} pagination={pagination} />
                <Modal
                    title={`添加/修改分类`}
                    visible={FormModalVisible}
                    cancelText="取消"
                    okText="确认"
                    onOk={() => {
                        this.refs.categoryFormRef.validateFields().then(formData => {
                            if (formData.cover && formData.cover.file && formData.cover.file.status == "done") {
                                formData.cover = formData.cover.file.response.originalname;
                            }
                            if (isAdd) {
                                addCat(formData).then(res => {
                                    if (res.code == 200) {
                                        this.getAllCat_com();
                                        this.setState({
                                            FormModalVisible: false,
                                        });
                                        message.success("添加成功");
                                    } else {
                                        message.error(res.message);
                                    }
                                });
                            } else {
                                formData._id = editId;
                                updateCat(formData).then(res => {
                                    if (res.code == 200) {
                                        this.getAllCat_com();
                                        this.setState({
                                            FormModalVisible: false,
                                        });
                                        message.success("修改成功");
                                    } else {
                                        message.error(res.message);
                                    }
                                });
                            }
                        });
                    }}
                    onCancel={() =>
                        this.setState({
                            FormModalVisible: false,
                        })
                    }
                    keyboard={true}
                >
                    <Form ref="categoryFormRef" wrapperCol={{ span: 12 }} labelCol={{ span: 7 }} initialValues={{ orderIndex: 20 }}>
                        <FormItem name="title" label="分类名" rules={[{ required: true, message: "分类名不能为空" }]}>
                            <Input />
                        </FormItem>
                        <FormItem name="orderIndex" label="排序号" rules={[{ required: true, message: "排序号不能为空" }]}>
                            <Input type="number" maxLength={3} max={100} min={0} />
                        </FormItem>
                        <FormItem name="cover" label="分类图片">
                            <Upload
                                fileList={[]}
                                action={process.env.REACT_APP_FILE}
                                headers={{ Authorization: `Bearer ${localStorage[adminToken]}` }}
                                listType="picture-card"
                                onChange={info => {
                                    if (info.file.status == "done") {
                                        this.setState({ cover: info.file.response.originalname });
                                    }
                                }}
                            >
                                {cover ? <img width="100%" src={`${process.env.REACT_APP_FILE}/${cover}`} /> : <PlusOutlined />}
                            </Upload>
                        </FormItem>
                    </Form>
                </Modal>
            </>
        );
    }
}

export default Category;
